package com.atguigu.msm.controller;

import com.atguigu.common.Result;
import com.atguigu.msm.entity.UcenterMember;
import com.atguigu.msm.service.MsmCacheService;
import com.atguigu.msm.service.MsmService;
import com.atguigu.msm.service.UcenterMemberService;
import com.atguigu.serviceBase.exception.GuliException;
import com.atguigu.utils.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信服务控制器
 *
 * @author Summerday
 */
@RestController
@RequestMapping("/eduMsm/msm")
@CrossOrigin
public class MsmController {

    @Resource
    private MsmService msmService;

    @Resource
    private MsmCacheService msmCacheService;

    @Resource
    private UcenterMemberService ucenterMemberService;

    /**
     * 发送短信
     */
    @GetMapping("/send/{phone}")
    public Result sendMsm(@PathVariable("phone") String phone) {

        //判断手机号是否存在
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", phone);
        if (ucenterMemberService.count(wrapper) > 0) {
            throw new GuliException("手机号已注册");
        }
        //从redis中获取验证码,如果获取到直接返回
        String authCode = msmCacheService.getAuthCode(phone);

        if (!StringUtils.isEmpty(authCode)) {
            return Result.ok();
        }
        //生成随机验证码
        authCode = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", authCode);
        //生成随机值,传递给阿里云发送
        if (!msmService.sendMsm(param, phone)) {
            return Result.error().message("短信发送失败");
        }
        //存入redis
        msmCacheService.setAuthCode(phone, authCode);
        return Result.ok();
    }


}
